<template>
  <n-select
      v-model:value="curTags"
      v-bind="$attrs"
      multiple
      remote
      size="small"
      placeholder="请选择标签"
      filterable
      :render-tag="renderTag"
      :options="options"
      @search="handleSearch"
  />
</template>

<script setup lang="ts">

import {computed, h, onMounted, ref} from "vue";
import {NTag, SelectRenderTag} from "naive-ui";
import api from "@/api";

const props = defineProps({
  tags: {
    type: Array,
    default: [],
  }
})

onMounted(() => {
  handleSearch('')
})
const emits = defineEmits(['update:tags'])

const options = ref([])
const loading = ref(false)
const renderTag: SelectRenderTag = ({option, handleClose}) => {
  return h(
      NTag,
      {
        type: option.type as 'success' | 'warning' | 'error',
        size:'small',
        closable: true,
        onMousedown: (e: FocusEvent) => {
          e.preventDefault()
        },
        onClose: (e: MouseEvent) => {
          e.stopPropagation()
          handleClose()
        }
      },
      {default: () => option.label}
  )
}
const handleSearch = (query: string) => {
  loading.value = true
  api.tag.queryList({
    pageNo: 1,
    pageSize: 5,
    andParams: JSON.stringify({name: '%' + query + '%'})
  }).then(res => {
    let list = res.data.data.records
    options.value = list.reduce((prev: any, curr: any) => {
      let tmp = {
        label: curr.name,
        value: curr.name,
        id: curr.id,
        name: curr.name,
      };
      if (!prev.some((option: any) => option.value === tmp.value)) {
        prev.push(tmp);
      }
      return prev;
    }, options.value);
  }).finally(() => {
    loading.value = false
  })
}
const curTags = computed({
  get() {
    return props.tags
  },
  set(val: any) {

    emits('update:tags', val)
  }
})
</script>

<style scoped>

</style>